//
//  HMEmotionKeyboard.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let HMEmotionCollectionViewCellId = "HMEmotionCollectionViewCellId"

class HMEmotionKeyboard: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        HMEmoticonKeyboardViewModel.sharedViewModel
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(pageControl)
        
        toolBar.snp_makeConstraints { (make) in
            make.bottom.left.right.equalTo(self)
            make.height.equalTo(37)
        }
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(emoticonCollectionView.snp_centerX)
            make.bottom.equalTo(emoticonCollectionView)
        }
        
        // 主队列异步，其中的闭包会在主线程空闲的时候执行。
        // 主线程什么时候空闲呢？就是界面已经加载完成了
        DispatchQueue.main.async {
            // 将collectionView滚动到指定的组
            let indexPath = IndexPath(item: 0, section: 1)
            // 滚动到对应的组
            self.emoticonCollectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
            self.toolBar.selectedIndexPath = indexPath
        }
 

    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 为什么要在这个地方去设置layout的itemSize，因为在这个地方可以取到collectioView的大小
        let layout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = emoticonCollectionView.frame.size
    }
    
    /// 设置pageControl的显示数据
    ///
    /// - parameter indexPath: <#indexPath description#>
    func setPageControl(indexPath: IndexPath) {
        
        // 1. 设置总页数
        pageControl.numberOfPages = HMEmoticonKeyboardViewModel.sharedViewModel.allEmotions[indexPath.section].count
        // 2. 设置当前选中的页数
        pageControl.currentPage = indexPath.row
        // 3. 如果是第0组，就隐藏
        pageControl.isHidden = indexPath.section == 0
    }

    
    // MARK: - 懒加载控件
    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        // 关闭用户交互
        pageControl.isUserInteractionEnabled = false
        
        //        pageControl.currentPageIndicatorTintColor = UIColor.red
        //        pageControl.pageIndicatorTintColor = UIColor.black
        
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        pageControl.numberOfPages = 4
        
        return pageControl
    }()

    
    internal lazy var emoticonCollectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        // 设置间距
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        // 设置滚动方向
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        // 设置数据源
        collectionView.dataSource = self
        collectionView.delegate = self
        // 注册cell
        collectionView.register(HMEmotionCell.self, forCellWithReuseIdentifier: HMEmotionCollectionViewCellId)
        // 开启分页
        collectionView.isPagingEnabled = true
        
        // 关闭弹簧效果
        collectionView.bounces = false
        // 取消滚动条
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        return collectionView
    }()
    
    internal lazy var toolBar: HMEmoticonToolBar = {
        let toolBar = HMEmoticonToolBar()
        toolBar.emotionTypeChangedClosure = { (type) -> () in
            print("切换按钮点击了\(type)")
            
            // 将collectionView滚动到指定的组
            let indexPath = IndexPath(item: 0, section: type.rawValue)
            // 滚动到对应的组
            self.emoticonCollectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
            // 在点击的时候去设置pageControl
            self.setPageControl(indexPath: indexPath)
            
        }
        return toolBar
    }()
}

extension HMEmotionKeyboard: UICollectionViewDataSource,UICollectionViewDelegate {
    
    // 返回有多少组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return HMEmoticonKeyboardViewModel.sharedViewModel.allEmotions.count
    }

    
    // 代表对应的section有多个item，多少页
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonKeyboardViewModel.sharedViewModel.allEmotions[section].count
    }

    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMEmotionCollectionViewCellId, for: indexPath) as! HMEmotionCell
        cell.backgroundColor = RandomColor
        // 设置indexPath，显示当前cell是第几组第几页
        cell.indexPath = indexPath
        // 设置表情数据
        cell.emoticons = HMEmoticonKeyboardViewModel.sharedViewModel.allEmotions[indexPath.section][indexPath.item]
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 取到可见的cell
        let cells = emoticonCollectionView.visibleCells
        if cells.count == 2 {
            
            // 取到这两个cell
            let firstCell = cells.first!
            let lastCell = cells.last!
            
            // 要判断这两个Cell哪一个cell在界面上显示得多
            print(firstCell.center.x)
            // 按照刚才的思路，是哪一个cell的中心点在屏幕之上，就代表哪一个cell显示得多
            
            let screenRect = UIScreen.main.bounds
            // 将取到第1个cell的中心点，减去滚动的距离
            let x = firstCell.center.x - scrollView.contentOffset.x
            let firstPoint = CGPoint(x: x, y: firstCell.center.y)
            
            
            let indexPath: IndexPath
            // 判断中心点是否在屏幕的范围之内
            if screenRect.contains(firstPoint) {
                indexPath = emoticonCollectionView.indexPath(for: firstCell)!
            }else{
                indexPath = emoticonCollectionView.indexPath(for: lastCell)!
            }
            print("当前显示第\(indexPath.section)组的表情")
            // 选中toolBar中对应的section的按钮
           self.toolBar.selectedIndexPath = indexPath
           self.setPageControl(indexPath: indexPath)
        }
    }

    
}
